import requests
import random

# 定义目标 URL 和参数列表
url = "http://10.10.1.53:8000/test/sof/status/{}"
params = [200, 201, 202, 301, 404, 401, 500, 502, 503]


# 定义成功与失败的条件
def is_success(c):
    return str(c).startswith('2') or str(c).startswith('3')


def send_requests(num_requests):
    success_count = 0
    failure_count = 0

    for _ in range(num_requests):
        # 随机选择一个 c 值
        c = random.choice(params)
        # 发送 HTTP POST 请求
        try:
            response = requests.post(url.format(c))
            # 根据响应状态判断成功或失败
            if is_success(c):
                success_count += 1
            else:
                failure_count += 1

            print(f"Request with c={c}, Status Code: {response.status_code}")

        except requests.exceptions.RequestException as e:
            print(f"请求失败: {e}")
            failure_count += 1  # 将请求失败计入失败次数

    return success_count, failure_count


def main():
    num_requests = int(input("请输入请求次数: "))  # 用户输入请求次数
    success_count, failure_count = send_requests(num_requests)

    # 计算成功率和失败率
    total_requests = success_count + failure_count
    success_rate = (success_count / total_requests * 100) if total_requests > 0 else 0
    failure_rate = (failure_count / total_requests * 100) if total_requests > 0 else 0

    # 输出结果
    print(f"\n总请求次数: {total_requests}")
    print(f"成功次数: {success_count}")
    print(f"失败次数: {failure_count}")
    print(f"成功率: {success_rate:.2f}%")
    print(f"失败率: {failure_rate:.2f}%")


if __name__ == "__main__":
    main()
